package com.ssmdemo.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ssmdemo.constants.ResultCode;
import com.ssmdemo.exception.AddDataException;
import com.ssmdemo.exception.NullException;
import com.ssmdemo.exception.UpdateException;
import com.ssmdemo.mapper.TUserMapper;
import com.ssmdemo.pojo.TUsers;
import com.ssmdemo.pojo.check.CheckType;
import com.ssmdemo.service.TUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.List;

/**
 * @Author 咕唧
 * @Date 2022/5/24 16:26
 * @Version 1.0
 */
@Service
@Transactional//开启事务
public class TUserServiceImpl implements TUserService {

    private TUserMapper tUserMapper;

    @Autowired
    public void settUserMapper(TUserMapper tUserMapper) {
        this.tUserMapper = tUserMapper;
    }

    @Override
    public TUsers findById(Long id) {
        TUsers tUsers = tUserMapper.findById(id);
        Assert.notNull(tUsers, () -> {
            throw new NullException("查询数据为空", ResultCode.DATA_SELECT_NULL);
        });
        return tUsers;
    }

    @Override
    public void addUser(TUsers tUser) {

        //断言数据不为空，否则抛出异常
        Assert.isTrue(!tUser.isEmpty(CheckType.ADD), () -> {
            throw new AddDataException("没有传递必要数据", ResultCode.DATA_NULL);
        });
        tUserMapper.addUser(tUser);
    }

    @Override
    public void updateUser(TUsers tUser) {
        //数据校验
        Assert.isTrue(!tUser.isEmpty(CheckType.UPDATE), () -> {
            throw new UpdateException("没有传递必要的更新数据", ResultCode.DATA_UPDATE_NULL);
        });
        tUserMapper.updateUser(tUser);
    }

    @Override
    public PageInfo<TUsers> findAll(int pageSize, int pageNum) {
        //开启分页查询
        PageHelper.startPage(pageNum, pageSize);
        List<TUsers> usersList = tUserMapper.findAll();
        PageInfo<TUsers> pageInfo=new PageInfo<>(usersList);
        return pageInfo;
    }
}
